package com.kaili.controller.pda.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.response.ResponseData;
import com.kaili.common.util.CommonUtil;
import com.kaili.common.util.FreemarkUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.ValidList;
import com.kaili.db.service.*;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.pojo.dto.stowage.*;
import com.kaili.pojo.entity.BaseCar;
import com.kaili.pojo.entity.HsEwbSub;
import com.kaili.pojo.entity.HsEwbsStowageSub;
import com.kaili.pojo.vo.*;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.math.BigDecimal;
import java.util.*;

import static com.kaili.except.ResponseStatus.RESPONSE_DATA_EMPTY;

@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController("stowageControllerP")
@Api(tags = "[pda]配载发车服务", description = "[PDA]配载发车相关API")
@Validated
public class StowageController {

    @Autowired
    private MessageSource messageSource;

    @Autowired
    IHsEwbsStowageService stowageService;

    @Autowired
    IBaseCarService carService;

    @Autowired
    IHsEwbSubService ewbSubService;

    @Autowired
    ILoginUserInfoService loginUserInfoService;

    @PostMapping(value = "/p/stowages/bat")
    @ApiOperation(value = "[PDA]批量新增配载发车", notes = "[PDA]批量新增配载发车")
    public List<Map<String,Object>> doAddNewStowageByPad(@Validated @RequestBody ValidList<StowageAddPdaDTO> list) throws BaseExcept{
        List<Map<String,Object>> responList=new ArrayList<>();
        for (StowageAddPdaDTO addDTO:list) {
            Map<String,Object> map=new HashMap<>();
            map.put("stowageNo",addDTO.getStowageNo());
            try {
                StowageAddBean addBean=new StowageAddBean();
                BeanUtils.copyProperties(addDTO,addBean);
                //加入配载单制作网点ID和制作人ID
                addBean.setUserId(loginUserInfoService.getLoginUserId());
                addBean.setSiteId(loginUserInfoService.getLoginSiteId());
                ResponseData status = doAddStowageByPad(addBean);
                //如果配载成功 进行发车
                if(status.getStatus()==200){
                    List<String>  operationIds=new ArrayList<>();
                    operationIds.add(addBean.getOperationId());
                    ResponseStatus responseStatus = doConfirmSend(operationIds);
                    map.put("status",responseStatus.getCode());
                    map.put("message",messageSource.getMessage(responseStatus.getMsg(), null, CommonUtil.getLocale()));
                    map.put("data",null);
                }else {
                    map.put("status",status.getStatus());
                    map.put("message",status.getMessage());
                    map.put("data",status.getData());
                }
            }catch (BaseExcept e){
                map.put("status",e.getResponseStatus().getCode());
                map.put("message",messageSource.getMessage(e.getResponseStatus().getMsg(), null, CommonUtil.getLocale()));
                map.put("data",null);
            }

            responList.add(map);
        }
        return responList;
    }

    @GetMapping("/p/stowages/{stowageNo}")
    @ApiOperation(value = "[PDA]分页查询配载数据列表")
    public StowageQueryPdaVO queryStowageList(@Pattern(regexp = "^[A-Za-z0-9]{0,30}$",message = "配载单号应为[A-Za-z0-9]组成的1-30位字符")@PathVariable("stowageNo")@ApiParam("配载单号") String stowageNo) throws BaseExcept {
            Map<Object,Object> param=new HashMap<>();
            List<String> strlist=new ArrayList<>();
            strlist.add(stowageNo);
            param.put("stowageList",strlist);
            param.put("status",0);
            param.put("siteId", LoginDetailUtils.getSiteId());
            Page<StowageQueryVO> pager = new Page<StowageQueryVO>(0, 15);
            pager = stowageService.queryStowagePageList(pager,param);

            StowageQueryPdaVO stowageQueryPdaVO = null;
            //查询配载单对应的主单信息
            if(pager.getRecords().size()>0){
                stowageQueryPdaVO=new StowageQueryPdaVO();
                StowageQueryVO stowageQueryVO = pager.getRecords().get(0);
                BeanUtils.copyProperties(stowageQueryVO,stowageQueryPdaVO);
                Map searchMap = new HashMap();
                searchMap.put("operationId", stowageQueryVO.getOperationId());
                List<StowageDetailPdaVO> list = stowageService.queryStowageDetailByPda(searchMap);
                //查询配载单对应的子单信息
                for (StowageDetailPdaVO stowageDetailPdaVO:list) {
                    Map subMap= new HashMap();
                    searchMap.put("operationId", stowageQueryVO.getOperationId());
                    searchMap.put("ewbNo",stowageDetailPdaVO.getEwbNo());
                    List<String> subList = stowageService.queryStowageSubEwbByPda(searchMap);
                    stowageDetailPdaVO.setSubList(subList);
                }
                stowageQueryPdaVO.setStowageDetailPdaVo(list);


            }
            return stowageQueryPdaVO;
    }

    public ResponseData  doAddStowageByPad(StowageAddBean addBean) throws BaseExcept{
        List<StowageDetailAddBean> stowageDetailList=new ArrayList<>();
        //记录不存在的子单号
        List<String> noExistSubList=new ArrayList<>();
        List<String> subEwbs = addBean.getSubEwbs();
        for (String ewbSubNo:subEwbs) {
            HsEwbSub hsEwbSub = ewbSubService.selectEwbNo(ewbSubNo);
            //如果子单号不存在
            if(hsEwbSub==null){
                noExistSubList.add(ewbSubNo);
            }else{
                SetStowageDetail(stowageDetailList,hsEwbSub);
            }
        }

        //如果有不存的子单号
        if(noExistSubList.size()>0){
            ResponseData responseData=new ResponseData();
            responseData.setStatus(ResponseStatus.SUB_EWB_NOT_EXIST.getCode());
            responseData.setMessage(messageSource.getMessage(ResponseStatus.SUB_EWB_NOT_EXIST.getMsg(), null, CommonUtil.getLocale()));
            responseData.setData(noExistSubList);
            return responseData;
        }

        //设置信息补全
        BigDecimal outWeight=new BigDecimal(0.00);
        BigDecimal outVo=new BigDecimal(0.00);

        for (StowageDetailAddBean stowageDetail:stowageDetailList){
            outWeight=outWeight.add(stowageDetail.getStowageWeight());
            outVo=outVo.add(stowageDetail.getStowageVol());
        }
        addBean.setOutEwbCount(stowageDetailList.size());
        addBean.setOutWeight(outWeight);
        addBean.setOutVol(outVo);
        addBean.setEwbsStowageDetailList(stowageDetailList);

        //直接调用接口新增
        ResponseStatus responseStatus =null;
        int ret = stowageService.doAddStowage(addBean);
        if (ret != 0) {
            responseStatus=ResponseStatus.STOWAGE_ADD_ERR;
        }else{
            responseStatus=ResponseStatus.RESPONSE_OK;
        }

        ResponseData responseData=new ResponseData();
        responseData.setStatus(responseStatus.getCode());
        responseData.setMessage(messageSource.getMessage(responseStatus.getMsg(), null, CommonUtil.getLocale()));
        return responseData;
    }

    public ResponseStatus doConfirmSend(List<String>  operationIds) {
        int ret = stowageService.doConfirmSend(operationIds);
        if (ret != 0) {
            return ResponseStatus.STOWAGE_CONFIRM_ERR;
        }
        BaseCar baseCar;
        for(String  operationId:operationIds){
            baseCar = new BaseCar();
            baseCar.setId(stowageService.selectById(operationId).getCarId());
            baseCar.setCarStatus("在途");
            carService.updateById(baseCar);
        }
        return ResponseStatus.RESPONSE_OK;
    }


    public void SetStowageDetail(List<StowageDetailAddBean> list, HsEwbSub hsEwbSub){
        for (StowageDetailAddBean stowageDetail: list) {
            //如果存在运单号
            if(hsEwbSub.getEwbNo().equals(stowageDetail.getEwbNo())){
                //累计件数
                stowageDetail.setStowagePiece(stowageDetail.getStowagePiece()+1);
                //累计体积
                BigDecimal stowageVol = stowageDetail.getStowageVol().add(hsEwbSub.getVol());
                stowageDetail.setStowageVol(stowageVol);
                //累计重量
                BigDecimal stowageWeight = stowageDetail.getStowageWeight().add(hsEwbSub.getWeight());
                stowageDetail.setStowageWeight(stowageWeight);
                //加入子单号
                stowageDetail.getSubEwbs().add(hsEwbSub.getSubEwb());
                return;
            }
        }
        //如果不能在则新增
        StowageDetailAddBean stowageDetail=new StowageDetailAddBean();
        stowageDetail.setEwbNo(hsEwbSub.getEwbNo());
        stowageDetail.setStowagePiece(1);
        stowageDetail.setStowageWeight(hsEwbSub.getWeight());
        stowageDetail.setStowageVol(hsEwbSub.getVol());
        //添加子单号
        List<String> subEwbs=new ArrayList<>();
        subEwbs.add(hsEwbSub.getSubEwb());
        stowageDetail.setSubEwbs(subEwbs);
        list.add(stowageDetail);
    }
}
